﻿namespace ConsoleApp.Tree;

public static class TreeBuilder
{
    public static TreeNode<T> BuildTree<T>(
        IEnumerable<(T Data, int? ParentId)> nodes)
    {
        var nodeMap = nodes.ToDictionary(
            node => node.Data, 
            node => new TreeNode<T>(node.Data));
        
        var root = nodeMap.Values.FirstOrDefault(n => 
            !nodes.Any(x => x.ParentId != null && x.Data.Equals(n.Current)));
        
        foreach (var (data, parentId) in nodes)
        {
            if (parentId.HasValue)
            {
                var parent = nodeMap.Values.FirstOrDefault(
                    n => n.Current.Equals(data));
                var child = nodeMap.Values.FirstOrDefault(
                    n => n.Current.Equals(data));
                parent?.AddChild(child);
            }
        }
        return root;
    }
}